package com.gitee.wsl.ext.map

import com.gitee.wsl.ext.base.Compare
import com.gitee.wsl.ext.collection.assoc


fun <K, V> Map<K, V>.sortByKey(comparator: Comparator<K>)=
    this.entries.sortedWith(MapEntryComparator.key(comparator)).assoc { it.key to it.value }

fun <K, V> Map<K, V>.sortByValue(comparator: Comparator<V>)=
    this.entries.sortedWith(MapEntryComparator.value(comparator)).assoc { it.key to it.value }




abstract class MapEntryComparator<A, V>:Comparator<Map.Entry<A, V>>{

    companion object{
        fun <K,V> key(comparator: Comparator<K>): MapEntryComparator<K, V> {
            return object: MapEntryComparator<K, V>() {
                override fun compare(a: Map.Entry<K, V>, b: Map.Entry<K, V>): Int {
                    return comparator.compare(a.key, b.key)
                }
            }
        }

        fun <K,V> value(comparator: Comparator<V>): MapEntryComparator<K, V> {
            return object: MapEntryComparator<K, V>() {
                override fun compare(a: Map.Entry<K, V>, b: Map.Entry<K, V>): Int {
                    return comparator.compare(a.value, b.value)
                }
            }
        }

    }
}